#include "originalform.h"
#include <QDateTime>
#include <QDir>
#include <QFileDialog>
#include <QDebug>

OriginalForm::OriginalForm(QWidget *parent)
    : QWidget(parent)
{
    initBasicUI();
    initSlots();
}

void OriginalForm::initBasicUI()
{
    keyList = new QList<QLineEdit*>();
    valueList = new QList<QLineEdit*>();
    creatorHistList = new QList<QLineEdit*>();
    changesHistList = new QList<QLineEdit*>();
    histTimerList = new QList<QDateTime>();

    mainLayout = new QVBoxLayout(this);
    setLayout(mainLayout);
    fLayout = new QFormLayout(this);
    histLayout = new QGridLayout(this);
    newAttrLayout = new QGridLayout(this);
    bottomLayout = new QHBoxLayout(this);
    mainLayout->addLayout(fLayout);
    mainLayout->addLayout(newAttrLayout);
    mainLayout->addLayout(histLayout);
    mainLayout->addLayout(bottomLayout);

    basePathBtn = new QPushButton("Select Folder Path");
    fLayout->addWidget(basePathBtn);
    locationLabel = new QLabel("Location: ");
    fLayout->addWidget(locationLabel);
    titleLabel = new QLabel("Title");
    title = new QLineEdit();
    fLayout->addRow(titleLabel, title);

    intstLabel = new QLabel("Instrument");
    instruments = new QLineEdit();
    fLayout->addRow(intstLabel, instruments);

    creatorLabel = new QLabel("Creator");
    creator = new QLineEdit();
    QString user = QDir::home().dirName();
    creator->setText(user);
    fLayout->addRow(creatorLabel, creator);

    creationDate = new QLineEdit();
    dateLabel = new QLabel("Creation Date");
    QDateTime local(QDateTime::currentDateTime());
    QString localTime = local.toString("yyyy-MM-dd hh:mm:ss");
    creationDate->setText(localTime);
    fLayout->addRow(dateLabel, creationDate);

    setLabel = new QLabel("Sets: ");
    QLabel placeholder("");
    fLayout->addRow(setLabel, &placeholder);

    typeLabel = new QLabel("Data Type");
    type = new QLineEdit();
    type->setEnabled(false);
    fLayout->addRow(typeLabel, type);

    formatLabel = new QLabel("Data Format");
    format = new QLineEdit();
    fLayout->addRow(formatLabel, format);

    comAllLabel = new QLabel("Comments");
    commentsAll = new QLineEdit();
    fLayout->addRow(comAllLabel, commentsAll);

    originLabel = new QLabel("Original path");
    origin = new QLineEdit();
    originPathBtn = new QToolButton;
    originPathBtn->setText("...");
    originPathBtn->setCursor(Qt::ArrowCursor);
    choosePathAction = new QWidgetAction(origin);
    choosePathAction->setDefaultWidget(originPathBtn);
    origin->addAction(choosePathAction, QLineEdit::TrailingPosition);
    fLayout->addRow(originLabel, origin);

    addNewAttrBtn = new QPushButton("New Attribute +");
    delNewAttrBtn = new QPushButton("Del Attribute -");
    newAttrLayout->addWidget(addNewAttrBtn, 0, 1, 2, 1);
    newAttrLayout->addWidget(delNewAttrBtn, 0, 3, 2, 1);

    delHistBtn = new QPushButton("Del History -");
    addHistBtn = new QPushButton("New History +");
    histLayout->addWidget(addHistBtn, 0, 1, 2, 1);
    histLayout->addWidget(delHistBtn, 0, 3, 2, 1);

    okBtn = new QPushButton("Generate");
    clearBtn = new QPushButton("Clear All");
    bottomLayout->addWidget(okBtn);
    bottomLayout->addWidget(clearBtn);
//    hLayout = new QHBoxLayout(this);
//    rawRadioBtn = new QRadioButton("Original Set");
//    trainRadioBtn = new QRadioButton("Training Set");
//    testRadioBtn = new QRadioButton("Testing Set");
//    hLayout->addWidget(rawRadioBtn);
//    hLayout->addWidget(trainRadioBtn);
//    hLayout->addWidget(testRadioBtn);
//    fLayout->addItem(hLayout);
}


void OriginalForm::initSlots(){
    connect(basePathBtn, &QPushButton::clicked, this, &OriginalForm::chooseFolderAction);
    connect(addNewAttrBtn, &QPushButton::clicked, this, &OriginalForm::genAttrAction);
    connect(delNewAttrBtn, &QPushButton::clicked, this, &OriginalForm::delAttrAction);
    connect(addHistBtn, &QPushButton::clicked, this, &OriginalForm::genHistAction);
    connect(delHistBtn, &QPushButton::clicked, this, &OriginalForm::delHistAction);
    connect(okBtn, &QPushButton::clicked, this, &OriginalForm::genMetadataAction);
    connect(clearBtn, &QPushButton::clicked, this, &OriginalForm::clearMetadataAction);
}

void OriginalForm::chooseFolderAction(){
    QString folderName = QFileDialog::getExistingDirectory();
    locationLabel->setText("Location: " + folderName);
    QFileInfo metaFile(folderName + "/metadata.json");
    if (metaFile.exists()){
        operationDialog();
        if (optCode == UPDATE){
            parser = new MetaParser(metaFile.absoluteFilePath());
            parser->parseMetadata();
            title->setText(parser->name.toString());
            instruments->setText(parser->instruments.toString());
            creator->setText(parser->creator.toString());
            creationDate->setText(parser->createDate.toString());
            locationLabel->setText("Location: " + parser->location.toString());
            type->setText(parser->type.toString());
            format->setText(parser->format.toString());
            origin->setText(parser->origin.toString());
            for (int i = 0; i < parser->history.count(); ++i){
                genHistAction();
                QJsonObject hist = parser->history.at(i).toObject();
                creatorHistList->last()->setText(hist.value("creator").toString());
                changesHistList->last()->setText(hist.value("changes").toString());
            }
            for(QJsonObject::Iterator it = parser->newAttr->begin(); it != parser->newAttr->end(); ++it){
                genAttrAction();
                qDebug() << it.value();
                keyList->last()->setText(it.key());
                valueList->last()->setText(parser->toString(it.value()));
            }
        }
    }
}
void OriginalForm::genAttrAction(){
    QLabel *newKeyLabel = new QLabel("New Key");
    QLineEdit *key = new QLineEdit();

    QLabel *newValueLabel = new QLabel("New Value");
    QLineEdit *value = new QLineEdit();
    newAttrLayout->addWidget(newKeyLabel, keyList->length()+1, 0, 1, 1);
    newAttrLayout->addWidget(key, keyList->length()+1, 1, 1, 1);
    newAttrLayout->addWidget(newValueLabel, keyList->length()+1, 2, 1, 1);
    newAttrLayout->addWidget(value, keyList->length()+1, 3, 1, 1);

    keyList->append(key);
    valueList->append(value);
}

void OriginalForm::delAttrAction(){
    if (keyList->length() > 0 && valueList->length() > 0) {
        keyList->pop_back();
        valueList->pop_back();
        for (int i = 0; i < 4; i++){
            int num = newAttrLayout->count();
            QWidget *p = newAttrLayout->itemAt(num-1)->widget();
            newAttrLayout->removeWidget(p);
            delete p;
        }
    }
}

void OriginalForm::genHistAction(){
    QLabel *creatorHistLabel = new QLabel("Creator");
    QLineEdit* creatorHist = new QLineEdit();
    QString user = QDir::home().dirName();
    creatorHist->setText(user);
    histLayout->addWidget(creatorHistLabel, creatorHistList->length()+1, 0, 1, 1);
    histLayout->addWidget(creatorHist, creatorHistList->length()+1, 1, 1, 1);

    QLabel *changesHistLabel = new QLabel("Changes");
    QLineEdit* changesHist = new QLineEdit();
    histLayout->addWidget(changesHistLabel, creatorHistList->length()+1, 2, 1, 1);
    histLayout->addWidget(changesHist, creatorHistList->length()+1, 3, 1, 1);

    creatorHistList->append(creatorHist);
    changesHistList->append(changesHist);
    histTimerList->append(QDateTime::currentDateTime());
}

void OriginalForm::delHistAction(){
    if (!creatorHistList->isEmpty() && !changesHistList->isEmpty() && !histTimerList->empty()){
        creatorHistList->pop_back();
        changesHistList->pop_back();
        histTimerList->pop_back();
        for (int i = 0; i < 4; ++i){
            int num =  histLayout->count();
            QWidget *p = histLayout->itemAt(num-1)->widget();
            histLayout->removeWidget(p);
            delete p;
        }
    }

}

void OriginalForm::genMetadataAction(){

}


void OriginalForm::clearMetadataAction(){

}


void OriginalForm::operationDialog(){
    QDialog *dialog = new QDialog;
    dialog->setWindowTitle("Operation about metadata");
    QVBoxLayout *vLayout = new QVBoxLayout;
    dialog->setLayout(vLayout);

    QLabel *askLabel = new QLabel("Metadata in current Folder has been already created, "
                                      "would you like to?");
    QPushButton *overWriteBtn = new QPushButton("Overwrite");
    QPushButton *updateBtn = new QPushButton("Update");
    vLayout->addWidget(askLabel);
    vLayout->addWidget(overWriteBtn);
    vLayout->addWidget(updateBtn);
    connect(overWriteBtn, &QPushButton::clicked, [=]{
        this->optCode = OVERWRITE;
        dialog->close();
    });
    connect(updateBtn, &QPushButton::clicked, [=]{
        this->optCode = UPDATE;
        dialog->close();
    });
    dialog->exec();
    qDebug()<<optCode;
}
